﻿using fuzhu;
using LH.Models.APAR;
using LH.U8API.Bus; 
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;
using LH.Model.SA;
using ZDEntity;
using XXX.Models.AS;
using System.Diagnostics.Eventing.Reader;
using XXX.Models.WDFT;
using System.DirectoryServices.ActiveDirectory;
using System.Reflection;
using System.Security.Cryptography;
using System.Xml.Linq;
using LH.Model.PU;
using Newtonsoft.Json;
using XXX.Models.XXXEntities;
using Org.BouncyCastle.Ocsp;
using static XXX.Models.WDFT.WDFT_SaleOrderJinDu;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class PuBillVouchVM : PurBillVouch
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public PuBillVouchVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       

        public  RetModel2 Add()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前采购单号已存在" );
                }
                foreach(Body body in bodies)
                {
                    body.editprop = "A";
                }
            
                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
              
                //直接赋值了审核人，所以不需要再审核了
                if (!Pu_BillVouchDALCO.AddPurBillVouch(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //这个提示也认为是成功的
                    if (err== "add 下标越界")
                    {
                        return DBService.ReOKObject(ccode);
                    }
                    else
                    {
                        return DBService.ReErrObject("新增失败：" + err);
                    }
                }
             
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        /// <summary>
        /// 采购订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 Delete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前单据号不存在");
                }

                if (!Pu_BillVouchDALCO.VerifyPurBillVouch(ID, "delete", xmlConfig, out string err))
                {
                    return DBService.ReErrObject("删除失败：" + err);
                }
               
                return DBService.ReOKObject(head.cpbvcode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 采购发票 更改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 Modify()
        {
            try
            {
                string idcheck = "";
                if (!Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前单据号不存在");
                }

                head.pbvid = idcheck;
                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
                head.editprop = "M";
                //增加变更人
                //head.cchanger = head.cmaker;
                //head.dmoddate = head.ddate;


                //变更的处理， （1） 主键id，子表isosid写入（2）判断是新增，还是修改，还是删除 （3）时间戳读取


                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //取表头的时间戳
                    string sql = string.Format("select  cPBVMaker,cverifier, convert(char,convert(money,ufts),2) ufts from purbillvouch where cPBVCode = '{0}' ", head.cpbvcode);
                    Head u8head = db.Ado.SqlQuery<Head>(sql).FirstOrDefault();
                    if (!string.IsNullOrEmpty( u8head.cpbvverifier))
                    {
                        throw new Exception("单据已审核，请先弃审后修改！");
                    }
                    head.ufts = u8head.ufts;  
                    //head.istatus = "1";
                    //取表体信息,默认全部是D，循环后，剩余是D的，再写入表体
                    //发票没有时间戳
                    sql = string.Format("select 'D' AS editprop,  ID,cdefine33   from purbillvouchs where PBVID = '{0}' ", idcheck);

                    List<Body> u8bodies = db.Ado.SqlQuery<Body>(sql);
                    int bmodify = 0;//编辑标记
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        bodies[i].id = idcheck;
                        bmodify = 0;
                        for (int j = 0; j < u8bodies.Count; j++)
                        {
                            if (bodies[i].cdefine33 == u8bodies[j].cdefine33)
                            {
                                //表体不需要时间戳
                                //bodies[i].dufts = u8bodies[j].dufts;
                                bodies[i].id = u8bodies[j].id;
                                bodies[i].editprop = "M";
                                u8bodies[j].editprop = "M";
                                bmodify = 1;
                                continue;
                            }
                        }
                        if (bmodify == 0)
                        {
                            bodies[i].editprop = "A";
                        }

                    }
                    //循环后检查删除的
                    for (int j = 0; j < u8bodies.Count; j++)
                    {
                        if (u8bodies[j].editprop == "D")
                        {
                            Body body = new Body();
                            body.id = idcheck;
                            body.editprop = "D";
                            //body.dufts = u8bodies[j].dufts;
                            body.id = u8bodies[j].id;
                            bodies.Add(body);
                        }
                    }

                }

                string err = "";
                if (!Pu_BillVouchDALCO.ModifyPurBillVouch(this, xmlConfig, out err, out string id, out string ccode))
                {

                    return DBService.ReErrObject("变更失败：" + err);
                }

                return DBService.ReOKObject("变更完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public PuBillVouchVM GetAddEntity(API_PuBillVouch obj, ref string cErr, ref string cCode)
        {

            try
            {
                
                if (string.IsNullOrWhiteSpace(obj.cPBVCode))
                {
                    cErr = "采购发票号不能为空";
                    return null;
                }
                cCode = obj.cPBVCode;
                if (string.IsNullOrWhiteSpace(obj.cMaker))
                {
                    cErr = "制单人不能为空";
                    return null;
                }
                if (string.IsNullOrWhiteSpace(obj.cVenCode))
                {
                    cErr = "供应商不能为空";
                    return null;
                } 
                
                PurBillVouch.Head head = new PurBillVouch.Head
                {
                    cpbvbilltype  = obj.cPBVBillType,
                    cpbvcode = obj.cPBVCode,
                    dpbvdate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cpersoncode = obj.cPersonCode,
                    cdepcode = obj.cDepCode,
                    cpbvmaker = obj.cMaker,
                    cvencode = obj.cVenCode,
                     cunitcode = obj.cVenCode,//代垫单位
                cpbvmemo = obj.cMemo,
                    cbustype = "普通采购",
                    csource="采购",
                    cptcode = obj.cPTCode,
                    iswfcontrolled = "0",
                    cexch_name = string.IsNullOrEmpty(obj.cExchname) ? "人民币" : obj.cExchname,
                    cexchrate = string.IsNullOrEmpty(DbHelper.GetDbString(obj.iExchrate)) ? "1" : DbHelper.GetDbString(obj.iExchrate),
                    ivtid = "8163",
                    idiscounttaxtype = "0",
                    
                cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };
              
                head.dvoudate = obj.dVouDate ;
                head.bnegative = "0";
                head.boriginal = "0";
                head.bfirst = "0";
                head.bsettle = "0";
                head.iflowid = "0";
                head.iswfcontrolled = "0";
                head.ireturncount = "0";
                head.bmerger = "0";
                head.iverifystateex = "0";
                List<PurBillVouch.Body> bodies = new List<PurBillVouch.Body>();
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    if (obj.itemList != null && obj.itemList.Count > 0)
                    {

                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            PurBillVouch.Body body = new PurBillVouch.Body
                            {
                                 //来源于入库单，rd
                                upsotype = item.upsotype,
                                cinvcode= item.cInvCode,
                                //body.cfree1 = item.cFree1;
                                //body.bgsp = model.materialList[i].checkid;
                                //body.dpdate = item.manufactureDate;
                               ipbvquantity =DbHelper.GetDbString(item.iQuantity),
                                inum = DbHelper.GetDbString(item.iNum),
                                citem_class = item.cItem_Class,
                                citemcode = item.cItemCode,
                              
                                //body.ccode = DbHelper.GetDbString(item.iRdsid);
                               editprop = "A",
                               bservice = "0",
                               itaxrate = item.iTaxRate,
                               ivouchrowno = item.iRowNo,
                               ioricost =DbHelper.GetDbString(item.iOriUnitPrice),
                               ioritaxcost = DbHelper.GetDbString(item.iOriTaxUnitPrice),
                               iorimoney = DbHelper.GetDbString(item.iOriMoney),
                               ioritaxprice = DbHelper.GetDbString(item.iOriTax),
                               iorisum = DbHelper.GetDbString(item.iOriSum),
                               icost = DbHelper.GetDbString(item.iNatUnitPrice),
                               imoney = DbHelper.GetDbString(item.iNatMoney),
                               itaxprice = DbHelper.GetDbString(item.iNatTaxUnitPrice),
                               isum = DbHelper.GetDbString(item.iNatSum),
                               cbmemo = item.cBMemo,
                               bgift = "0",
                               isPayment = "0",
                               isSettle = "0",
                               bcosting = "0",
                               btaxcost = "0",
                               brettax = "0",
                            //当前行id
                            cdefine31 = item.cRowId,
                                //从22 写到37
                                cdefine22 = item.cDefine22,
                                cdefine23 = item.cDefine23,
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                
                                cdefine32 = item.cDefine32,
                                
                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37
                            };
                        //采购入库单关联处理
                        if (item.upsotype == "rd")
                        { 
                                if ( string.IsNullOrEmpty(item.cSoureRowId))
                                {

                                    throw new Exception($"{obj.cPBVCode}物料{item.cInvCode},无入库单来源行ID");
                                }
                                 
                             
                            var row = db.Queryable<RdRecords01>().Where(x => x.cDefine31 == item.cSoureRowId).First();
                                if (row==null)
                                {
                                    throw new Exception($"{obj.cPBVCode}物料{item.cInvCode},来源行ID{item.cSoureRowId}无法关联到入库单");
                                }
                                else
                                {
                                    body.rdsid = row.AutoID.ToString();
                                    body.iposid = row.iPOsID.ToString();
                                } 
                        }
                        else
                            {
                                if (string.IsNullOrEmpty(item.cSoureRowId))
                                {

                                    throw new Exception($"{obj.cPBVCode}物料{item.cInvCode},无采购订单来源行ID");
                                }


                                var row = db.Queryable<PO_Podetails>().Where(x => x.cDefine31 == item.cSoureRowId).First();
                                if (row == null)
                                {
                                    throw new Exception($"{obj.cPBVCode}物料{item.cInvCode},来源行ID{item.cSoureRowId}无法关联到采购订单");
                                }
                                else
                                {
                                  
                                    body.iposid = row.ID.ToString();
                                }
                            }

                            bodies.Add(body);
                        }
                    }
                }
                PuBillVouchVM model = new PuBillVouchVM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public PuBillVouchVM GetCodeEntity(API_PuBillVouch obj, ref string cErr)
        {

            try
            {

                PurBillVouch.Head head = new PurBillVouch.Head();
                head.cpbvcode = obj.cPBVCode;
                List<PurBillVouch.Body> bodies = new List<PurBillVouch.Body>();

                PuBillVouchVM model = new PuBillVouchVM(head, bodies); 

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }
        /// <summary>
        /// 完善采购信息,处理部门，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetAddInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                #region  根据业务员取部门编码
                //if(!string.IsNullOrWhiteSpace(head.cpersoncode))
                //{
                //    Person person =db.Queryable<Person>().Where(x => x.cPersonCode == head.cpersoncode).First();
                //    if (person == null)
                //    {
                //        return string.Format("Error: 业务员编码{0}不存在", head.cpersoncode);
                //    }
                //    else
                //    {
                //        head.cdepcode = person.cDepCode;                         
                //    }
                //}

                #endregion

                  

                     
                    


                    for (int i = 0; i < bodies.Count; i++)
                {
                    string cInvCode = bodies[i].cinvcode;
                    Inventory inv = db.Queryable<Inventory>().Where(c => c.cInvCode == cInvCode).First();
                    if (inv == null)
                    {
                        return string.Format("Error: 第{0}行存货编码{1}不存在", (i + 1).ToString(), cInvCode);
                    }
                    #region 处理自由项6
                    //if(inv.bFree6)
                    //{
                    //    if (string.IsNullOrWhiteSpace(bodies[i].cfree6))
                    //    {
                    //        return string.Format("Error: 第{0}行存货编码{1}有自由项6，长度管理，请录入", (i + 1).ToString(), cInvCode);
                    //    }
                       
                    //}
                    //else
                    //{
                    //    bodies[i].cfree6 = "";
                    //}
                    #endregion

                    #region 处理辅助计量单位
                    bodies[i].cgroupcode = inv.cGroupCode;
                    bodies[i].igrouptype = DbHelper.GetDbString(inv.iGroupType);
                    //cunitid 不为空，则取存货档案的辅助计量单位
                    if (string.IsNullOrWhiteSpace(bodies[i].cunitid))
                    {
                        bodies[i].cunitid = inv.cSTComUnitCode;
                    }
                    //如果igrouptype！=0，则需要获取辅助单位换算率，并计算辅助数量
                    if (DbHelper.GetDbString(inv.iGroupType) != "0")
                    {
                        //换算率是空
                        if (string.IsNullOrWhiteSpace(bodies[i].iinvexchrate))
                        {
                            //并且件数也是空,取存货档案的换算率
                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].inum)) || bodies[i].inum == "0")
                            {
                                //获取辅助换算率
                                ComputationUnit unit = SqlsugarHelper.Instance.Queryable<ComputationUnit>().Where(x => x.cComunitCode == bodies[i].cunitid).First();

                                bodies[i].iinvexchrate = DbHelper.GetDbString(unit.iChangRate);
                            }
                            else
                            {
                                //件数不为空,根据数量/件数计算换算率
                                bodies[i].iinvexchrate = (DbHelper.GetDbdecimal(bodies[i].ipbvquantity) / DbHelper.GetDbdecimal(bodies[i].inum)).ToString("0.000000");
                            }

                        }
                        //件数： 有换算率，并且换算率不为0，件数是空的，计算辅助数量
                        if (!string.IsNullOrWhiteSpace(bodies[i].iinvexchrate) && bodies[i].iinvexchrate != "0" && string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].inum)))
                        {
                            //计算辅助数量, 小数位。。。。。
                            bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].ipbvquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                        }

                    }
                    #endregion

                    #region 处理税率
                    //税率，先取客户档案，如果客户档案为空，取存货档案; 都没有，币种是人民币的，默认税率是13

                    //if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].ipertaxrate)))
                    //{
                    //     if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(inv.iTaxRate)))
                    //    {
                    //        bodies[i].ipertaxrate = DbHelper.GetDbdecimal(inv.iTaxRate);
                    //    }


                    //}

                    #endregion

                    FitemVM fitemVM = new FitemVM();

                    if (fitemVM.GetName(bodies[i].citem_class, bodies[i].citemcode, out string citem_cname, out string citemname) == "ok")
                    {
                        bodies[i].citem_name = citem_cname;
                        bodies[i].citemname = citemname;
                    }


                }
            }
            
            return "ok";
        }

        /// <summary>
        /// 检查单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select PBVID from PurBillVouch where cpbvcode='{0}' ", head.cpbvcode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

         
    }
}
